using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Protobuf.WellKnownTypes;
using Task;

namespace task
{
    public partial class FormData : Form
    {
        public static bool RefreshListFlag = false;
        public List<Material> Materials { get; set; }
        public Dictionary<string, string> Subtypes { get; set; }
        public List<string> Types { get; set; }

        public FormData()
        {
            InitializeComponent();
        }

        public FormData(List<Material> materials, List<string> types, Dictionary<string, string> subtypes)
        {
            InitializeComponent();
            Materials = materials;
            Subtypes = subtypes;
            Types = types;
            InitTypes();
            InitSubTypes();
            SetCbxType();
            RefreshList();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void InitTypes()
        {
            Types = DbHandler.GetAllType();
        }

        private void InitSubTypes()
        {
            Subtypes = DbHandler.GetAllSubType();
        }

        private void SetCbxType()
        {
            cbx_TypeSearch.Items.Clear();
            cbx_cType.Items.Clear();
            foreach (var type in Types)
            {
                cbx_TypeSearch.Items.Add(type);
                cbx_cType.Items.Add(type);
            }
        }

        private void SetCbxSubtypeSearch()
        {
            //设置子类型搜索下拉列表物件
            cbx_SubTypeSearch.Items.Clear();
            foreach (var st in Subtypes.Where(st => st.Value == cbx_TypeSearch.Text))
            {
                cbx_SubTypeSearch.Items.Add(st.Key);
            }
        }

        private void SetCbxCSubtype()
        {
            cbx_cSubtype.Items.Clear();
            foreach (var st in Subtypes.Where(st => st.Value == cbx_cType.Text))
            {
                cbx_cSubtype.Items.Add(st.Key);
            }
        }

        private void RefreshList()
        {
            // refresh listbox
            lbx_Reasult.Items.Clear();
            //refresh list view
            lv_Reasult.Items.Clear();
            int i = 0;
            foreach (var material in Materials)
            {
                lbx_Reasult.Items.Add(++i + "." + material.Content);
                lv_Reasult.Items.Add(i + "." + material.Content);
            }
        }

        private void 查看内容ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                new FormInfomation(Materials[lbx_Reasult.SelectedIndex], false).Show();
            }
            catch (Exception)
            {
                MessageBox.Show("请选择一行数据!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Menu_Opening(object sender, CancelEventArgs e)
        {
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (lbx_Reasult.SelectedIndex < 0) throw new Exception("请选择至少一条数据！");
                var res = MessageBox.Show("您确定要删除这条数据吗？此操作将不可恢复。", "警告", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning);
                if (res == DialogResult.Yes)
                {
                    DbHandler.DeleteMaterial(Materials[lbx_Reasult.SelectedIndex]);
                    Materials.RemoveAt(lbx_Reasult.SelectedIndex);
                    MessageBox.Show("删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    RefreshList();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void 更改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new FormInfomation(Materials[lbx_Reasult.SelectedIndex], true).Show();
            new Thread(new ThreadStart(delegate
            {
                while (!RefreshListFlag)
                {
                }

                RefreshList();
                RefreshListFlag = false;
            })).Start();
        }

        private void 全部删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteAll();
        }

        private void DeleteAll()
        {
            if (Materials.Count == 0)
            {
                return;
            }

            var res1 = MessageBox.Show("您确定要删除所有数据吗？此操作将不可恢复。", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (res1 == DialogResult.Yes)
            {
                while (Materials.Count > 0)
                {
                    try
                    {
                        DbHandler.DeleteMaterial(Materials[0]);
                        Materials.RemoveAt(0);
                    }
                    catch (Exception ex)
                    {
                        var res2 = MessageBox.Show(ex.Message + ",是否继续执行删除操作？", "错误", MessageBoxButtons.YesNo,
                            MessageBoxIcon.Error);
                        if (res2 == DialogResult.No)
                        {
                            return;
                        }
                    }
                }

                MessageBox.Show("删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                RefreshList();
            }
        }

        private void Btn_Search_Click(object sender, EventArgs e)
        {
            string queryStr = txt_search.Text;
            Materials = DbHandler.Search(queryStr);
            RefreshList();
        }

        private void Btn_TypeSearch_Click(object sender, EventArgs e)
        {
            Materials = ckb_Subtype.Checked
                ? DbHandler.SubTypeSearch(cbx_TypeSearch.Text, cbx_SubTypeSearch.Text)
                : DbHandler.TypeSearch(cbx_TypeSearch.Text);

            RefreshList();
        }

        private void Ckb_Subtype_CheckedChanged(object sender, EventArgs e)
        {
            cbx_SubTypeSearch.Visible = ckb_Subtype.Checked;
        }

        private void Cbx_TypeSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetCbxSubtypeSearch();
        }

        private void 删除所有选择项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (lbx_Reasult.SelectedIndices.Count <= 0)
                {
                    throw new Exception("请至少选择一项！");
                }

                MessageBox.Show("您确定要删除所有选择项？此操作将不可恢复！", "警告",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                List<Material> mts = new List<Material>();

                foreach (int index in lbx_Reasult.SelectedIndices)
                {
                    try
                    {
                        DbHandler.DeleteMaterial(Materials[index]);
                        mts.Add(Materials[index]);
                    }
                    catch (Exception ex)
                    {
                        var res2 = MessageBox.Show(ex.Message + ",是否继续执行删除操作？", "错误", MessageBoxButtons.YesNo,
                            MessageBoxIcon.Error);
                        if (res2 == DialogResult.No)
                        {
                            return;
                        }
                    }
                }

                foreach (var material in mts)
                {
                    Materials.Remove(material);
                }

                MessageBox.Show("成功！");
                RefreshList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            lv_Reasult.View = View.List;
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            lv_Reasult.View = View.SmallIcon;
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            lv_Reasult.View = View.LargeIcon;
        }

        private void Btn_Title_Click(object sender, EventArgs e)
        {
            lv_Reasult.View = View.Tile;
        }

        private void 查看详细内容ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lv_Reasult.SelectedIndices.Count != 1)
            {
                MessageBox.Show("请只选择一项查看！");
                return;
            }

            new FormInfomation(Materials[lv_Reasult.SelectedIndices[0]], false).Show();
        }

        private void 删除所选项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (lv_Reasult.SelectedIndices.Count <= 0)
                {
                    throw new Exception("请至少选择一项！");
                }

                var res1 = MessageBox.Show("您确定要删除所有选择项？此操作将不可恢复！", "警告",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (res1 == DialogResult.No)
                {
                    return;
                }

                List<Material> mts = new List<Material>();

                foreach (int index in lv_Reasult.SelectedIndices)
                {
                    try
                    {
                        DbHandler.DeleteMaterial(Materials[index]);
                        mts.Add(Materials[index]);
                    }
                    catch (Exception ex)
                    {
                        var res2 = MessageBox.Show(ex.Message + ",是否继续执行删除操作？", "错误", MessageBoxButtons.YesNo,
                            MessageBoxIcon.Error);
                        if (res2 == DialogResult.No)
                        {
                            return;
                        }
                    }
                }

                foreach (var material in mts)
                {
                    Materials.Remove(material);
                }

                MessageBox.Show("成功！");
                RefreshList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Btn_LenSearch_Click(object sender, EventArgs e)
        {
            int max = Convert.ToInt32(num_max.Text);
            int min = Convert.ToInt32(num_min.Text);
            if (max <= min)
            {
                MessageBox.Show("最大长度必须大于最小长度！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            Materials = DbHandler.LengthSearch(min, max);
            RefreshList();
        }

        private void 删除所有ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteAll();
        }

        private void Btn_DateSearch_Click(object sender, EventArgs e)
        {
            DateTime date = Convert.ToDateTime(dtp_date.Text);
            Materials = DbHandler.DateSearch(date);
            RefreshList();
        }

        private void Btn_TitleSearch_Click(object sender, EventArgs e)
        {
            Materials = DbHandler.TitleSearch(txt_titleSearch.Text);
            RefreshList();
        }

        private void cbx_cType_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetCbxCSubtype();
        }

        private void btn_changeType_Click(object sender, EventArgs e)
        {
            try
            {
                if (cbx_cType.Text == "" || cbx_cSubtype.Text == "")
                {
                    throw new Exception("类型和子类型不能为空！");
                }

                var res = MessageBox.Show("您确定要全部更改吗？此操作将不可恢复！", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (res != DialogResult.Yes) return;
                foreach (Material material in Materials)
                {
                    try
                    {
                        material.Type = cbx_cType.Text;
                        material.SubType = cbx_cSubtype.Text;
                        DbHandler.UpdateMaterial(material);
                    }
                    catch (Exception ex)
                    {
                        var result = MessageBox.Show("出现异常错误：" + ex.Message + "\n您是否要继续当前操作？", "错误",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                        if (result == DialogResult.No)
                        {
                            return;
                        }
                    }
                }

                MessageBox.Show("成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void 只显示选择项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lv_Reasult.SelectedIndices.Count == 0)
            {
                MessageBox.Show("您没有选择任何项！");
            }

            var mt = (from int index in lv_Reasult.SelectedIndices select Materials[index]).ToList();
            Materials = mt;
            RefreshList();
        }

        private void FormData_FormClosing(object sender, FormClosingEventArgs e)
        {
            var res = MessageBox.Show("关闭数据管理器将会返回主界面，您确定返回吗？", "警告", MessageBoxButtons.OKCancel,
                MessageBoxIcon.Warning);
            if (res == DialogResult.Cancel)
            {
                e.Cancel = true;
                return;
            }

            e.Cancel = false;
            General.FormMain.Show();
        }

        private void btn_remove_Click(object sender, EventArgs e)
        {
            try
            {
                string pattern = @"" + txt_keywords.Text;
                ReplaceAllContents(pattern, "");
                MessageBox.Show("成功");
                RefreshList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败：" + ex.Message);
            }
        }


        private void ReplaceAllContents(string pattern, string to)
        {
            foreach (Material material in Materials)
            {
                material.Content = Regex.Replace(material.Content, pattern, to);
                DbHandler.UpdateMaterial(material);
            }
        }

        private void btn_replace_Click(object sender, EventArgs e)
        {
            try
            {
                string pattern = @"" + txt_keywords.Text;
                ReplaceAllContents(pattern, txt_repTo.Text);
                MessageBox.Show("成功");
                RefreshList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败：" + ex.Message);
            }
        }

        private void txt_search_TextChanged(object sender, EventArgs e)
        {
            txt_keywords.Text = txt_search.Text;
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                if (lv_Reasult.SelectedIndices.Count != 1)
                    throw new Exception("请只选择一项修改！");
                new FormInfomation(Materials[lv_Reasult.SelectedIndices[0]], true).Show();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}